home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume17 / gnugrep / part02 < prev    next >
Encoding:
Internet Message Format  |  1989-02-08  |  52.6 KB

  1. Subject:  v17i099:  Gnu E?GREP (it's fast), Part02/05
  2. Newsgroups: comp.sources.unix
  3. Sender: sources
  4. Approved: rsalz@uunet.UU.NET
  5.  
  6. Submitted-by: Mike Haertel <mike@wheaties.ai.mit.edu>
  7. Posting-number: Volume 17, Issue 99
  8. Archive-name: gnugrep/part02
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then unpack
  12. # it by saving it into a file and typing "sh file".  To overwrite existing
  13. # files, type "sh file -c".  You can also feed this as standard input via
  14. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  15. # will see the following message at the end:
  16. #        "End of shell archive."
  17. # Contents:  dfa.h grep.c
  18. # Wrapped by mike@odin on Wed Dec 14 21:25:47 1988
  19. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  20. if test -f 'dfa.h' -a "${1}" != "-c" ; then 
  21.   echo shar: Will not clobber existing file \"'dfa.h'\"
  22. else
  23. echo shar: Extracting \"'dfa.h'\" \(22427 characters\)
  24. sed "s/^X//" >'dfa.h' <<'END_OF_FILE'
  25. X/* dfa.h - declarations for GNU deterministic regexp compiler
  26. X   Copyright (C) 1988 Free Software Foundation, Inc.
  27. X                      Written June, 1988 by Mike Haertel
  28. X
  29. X               NO WARRANTY
  30. X
  31. X  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  32. XNO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  33. XWHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  34. XRICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  35. XWITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  36. XBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  37. XFITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  38. XAND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  39. XDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  40. XCORRECTION.
  41. X
  42. X IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  43. XSTALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  44. XWHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  45. XLIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  46. XOTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  47. XUSE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  48. XDATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  49. XA FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  50. XPROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  51. XDAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  52. X
  53. X        GENERAL PUBLIC LICENSE TO COPY
  54. X
  55. X  1. You may copy and distribute verbatim copies of this source file
  56. Xas you receive it, in any medium, provided that you conspicuously and
  57. Xappropriately publish on each copy a valid copyright notice "Copyright
  58. X (C) 1988 Free Software Foundation, Inc."; and include following the
  59. Xcopyright notice a verbatim copy of the above disclaimer of warranty
  60. Xand of this License.  You may charge a distribution fee for the
  61. Xphysical act of transferring a copy.
  62. X
  63. X  2. You may modify your copy or copies of this source file or
  64. Xany portion of it, and copy and distribute such modifications under
  65. Xthe terms of Paragraph 1 above, provided that you also do the following:
  66. X
  67. X    a) cause the modified files to carry prominent notices stating
  68. X    that you changed the files and the date of any change; and
  69. X
  70. X    b) cause the whole of any work that you distribute or publish,
  71. X    that in whole or in part contains or is a derivative of this
  72. X    program or any part thereof, to be licensed at no charge to all
  73. X    third parties on terms identical to those contained in this
  74. X    License Agreement (except that you may choose to grant more extensive
  75. X    warranty protection to some or all third parties, at your option).
  76. X
  77. X    c) You may charge a distribution fee for the physical act of
  78. X    transferring a copy, and you may at your option offer warranty
  79. X    protection in exchange for a fee.
  80. X
  81. XMere aggregation of another unrelated program with this program (or its
  82. Xderivative) on a volume of a storage or distribution medium does not bring
  83. Xthe other program under the scope of these terms.
  84. X
  85. X  3. You may copy and distribute this program or any portion of it in
  86. Xcompiled, executable or object code form under the terms of Paragraphs
  87. X1 and 2 above provided that you do the following:
  88. X
  89. X    a) accompany it with the complete corresponding machine-readable
  90. X    source code, which must be distributed under the terms of
  91. X    Paragraphs 1 and 2 above; or,
  92. X
  93. X    b) accompany it with a written offer, valid for at least three
  94. X    years, to give any third party free (except for a nominal
  95. X    shipping charge) a complete machine-readable copy of the
  96. X    corresponding source code, to be distributed under the terms of
  97. X    Paragraphs 1 and 2 above; or,
  98. X
  99. X    c) accompany it with the information you received as to where the
  100. X    corresponding source code may be obtained.  (This alternative is
  101. X    allowed only for noncommercial distribution and only if you
  102. X    received the program in object code or executable form alone.)
  103. X
  104. XFor an executable file, complete source code means all the source code for
  105. Xall modules it contains; but, as a special exception, it need not include
  106. Xsource code for modules which are standard libraries that accompany the
  107. Xoperating system on which the executable file runs.
  108. X
  109. X  4. You may not copy, sublicense, distribute or transfer this program
  110. Xexcept as expressly provided under this License Agreement.  Any attempt
  111. Xotherwise to copy, sublicense, distribute or transfer this program is void and
  112. Xyour rights to use the program under this License agreement shall be
  113. Xautomatically terminated.  However, parties who have received computer
  114. Xsoftware programs from you with this License Agreement will not have
  115. Xtheir licenses terminated so long as such parties remain in full compliance.
  116. X
  117. X  5. If you wish to incorporate parts of this program into other free
  118. Xprograms whose distribution conditions are different, write to the Free
  119. XSoftware Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  120. Xworked out a simple rule that can be stated here, but we will often permit
  121. Xthis.  We will be guided by the two goals of preserving the free status of
  122. Xall derivatives our free software and of promoting the sharing and reuse of
  123. Xsoftware.
  124. X
  125. X
  126. XIn other words, you are welcome to use, share and improve this program.
  127. XYou are forbidden to forbid anyone else to use, share and improve
  128. Xwhat you give them.   Help stamp out software-hoarding!  */
  129. X
  130. X#ifdef __STDC__
  131. X
  132. X/* Missing include files for GNU C. */
  133. X/* #include <stdlib.h> */
  134. Xtypedef int size_t;
  135. Xextern void *calloc(int, size_t);
  136. Xextern void *malloc(size_t);
  137. Xextern void *realloc(void *, size_t);
  138. Xextern void free(void *);
  139. X
  140. X#ifndef USG
  141. Xextern char *strchr(), *strrchr(), *memcpy();
  142. X#else
  143. Xextern char *index();
  144. X#endif
  145. X
  146. Xextern char *bcopy(), *bzero();
  147. X
  148. X#ifdef SOMEDAY
  149. X#define ISALNUM(c) isalnum(c)
  150. X#define ISALPHA(c) isalpha(c)
  151. X#else
  152. X#define ISALNUM(c) (isascii(c) && isalnum(c))
  153. X#define ISALPHA(c) (isascii(c) && isalpha(c))
  154. X#endif
  155. X
  156. X#else /* ! __STDC__ */
  157. X
  158. X#define const
  159. Xtypedef int size_t;
  160. Xextern char *calloc(), *malloc(), *realloc();
  161. Xextern void free();
  162. X
  163. X#ifndef USG
  164. Xextern char *strchr(), *strrchr(), *memcpy();
  165. X#else
  166. Xextern char *index();
  167. X#endif
  168. X
  169. Xextern char *bcopy(), *bzero();
  170. X
  171. X#define ISALNUM(c) (isascii(c) && isalnum(c))
  172. X#define ISALPHA(c) (isascii(c) && isalpha(c))
  173. X
  174. X#endif /* ! __STDC__ */
  175. X
  176. X/* 1 means plain parentheses serve as grouping, and backslash
  177. X     parentheses are needed for literal searching.
  178. X   0 means backslash-parentheses are grouping, and plain parentheses
  179. X     are for literal searching.  */
  180. X#define RE_NO_BK_PARENS 1
  181. X
  182. X/* 1 means plain | serves as the "or"-operator, and \| is a literal.
  183. X   0 means \| serves as the "or"-operator, and | is a literal.  */
  184. X#define RE_NO_BK_VBAR 2
  185. X
  186. X/* 0 means plain + or ? serves as an operator, and \+, \? are literals.
  187. X   1 means \+, \? are operators and plain +, ? are literals.  */
  188. X#define RE_BK_PLUS_QM 4
  189. X
  190. X/* 1 means | binds tighter than ^ or $.
  191. X   0 means the contrary.  */
  192. X#define RE_TIGHT_VBAR 8
  193. X
  194. X/* 1 means treat \n as an _OR operator
  195. X   0 means treat it as a normal character */
  196. X#define RE_NEWLINE_OR 16
  197. X
  198. X/* 0 means that a special characters (such as *, ^, and $) always have
  199. X     their special meaning regardless of the surrounding context.
  200. X   1 means that special characters may act as normal characters in some
  201. X     contexts.  Specifically, this applies to:
  202. X    ^ - only special at the beginning, or after ( or |
  203. X    $ - only special at the end, or before ) or |
  204. X    *, +, ? - only special when not after the beginning, (, or | */
  205. X#define RE_CONTEXT_INDEP_OPS 32
  206. X
  207. X/* Now define combinations of bits for the standard possibilities.  */
  208. X#define RE_SYNTAX_AWK (RE_NO_BK_PARENS | RE_NO_BK_VBAR | RE_CONTEXT_INDEP_OPS)
  209. X#define RE_SYNTAX_EGREP (RE_SYNTAX_AWK | RE_NEWLINE_OR)
  210. X#define RE_SYNTAX_GREP (RE_BK_PLUS_QM | RE_NEWLINE_OR)
  211. X#define RE_SYNTAX_EMACS 0
  212. X
  213. X/* The NULL pointer. */
  214. X#define NULL 0
  215. X
  216. X/* Number of bits in an unsigned char. */
  217. X#define CHARBITS 8
  218. X
  219. X/* First integer value that is greater than any character code. */
  220. X#define _NOTCHAR (1 << CHARBITS)
  221. X
  222. X/* INTBITS need not be exact, just a lower bound. */
  223. X#define INTBITS (CHARBITS * sizeof (int))
  224. X
  225. X/* Number of ints required to hold a bit for every character. */
  226. X#define _CHARSET_INTS ((_NOTCHAR + INTBITS - 1) / INTBITS)
  227. X
  228. X/* Sets of unsigned characters are stored as bit vectors in arrays of ints. */
  229. Xtypedef int _charset[_CHARSET_INTS];
  230. X
  231. X/* The regexp is parsed into an array of tokens in postfix form.  Some tokens
  232. X   are operators and others are terminal symbols.  Most (but not all) of these
  233. X   codes are returned by the lexical analyzer. */
  234. X#ifdef __STDC__
  235. X
  236. Xtypedef enum
  237. X{
  238. X  _END = -1,            /* _END is a terminal symbol that matches the
  239. X                   end of input; any value of _END or less in
  240. X                   the parse tree is such a symbol.  Accepting
  241. X                   states of the DFA are those that would have
  242. X                   a transition on _END. */
  243. X
  244. X  /* Ordinary character values are terminal symbols that match themselves. */
  245. X
  246. X  _EMPTY = _NOTCHAR,        /* _EMPTY is a terminal symbol that matches
  247. X                   the empty string. */
  248. X
  249. X  _BACKREF,            /* _BACKREF is generated by \<digit>; it
  250. X                   it not completely handled.  If the scanner
  251. X                   detects a transition on backref, it returns
  252. X                   a kind of "semi-success" indicating that
  253. X                   the match will have to be verified with
  254. X                   a backtracking matcher. */
  255. X
  256. X  _BEGLINE,            /* _BEGLINE is a terminal symbol that matches
  257. X                   the empty string if it is at the beginning
  258. X                   of a line. */
  259. X
  260. X  _ALLBEGLINE,            /* _ALLBEGLINE is a terminal symbol that
  261. X                   matches the empty string if it is at the
  262. X                   beginning of a line; _ALLBEGLINE applies
  263. X                   to the entire regexp and can only occur
  264. X                   as the first token thereof.  _ALLBEGLINE
  265. X                   never appears in the parse tree; a _BEGLINE
  266. X                   is prepended with _CAT to the entire
  267. X                   regexp instead. */
  268. X
  269. X  _ENDLINE,            /* _ENDLINE is a terminal symbol that matches
  270. X                   the empty string if it is at the end of
  271. X                   a line. */
  272. X
  273. X  _ALLENDLINE,            /* _ALLENDLINE is to _ENDLINE as _ALLBEGLINE
  274. X                   is to _BEGLINE. */
  275. X
  276. X  _BEGWORD,            /* _BEGWORD is a terminal symbol that matches
  277. X                   the empty string if it is at the beginning
  278. X                   of a word. */
  279. X
  280. X  _ENDWORD,            /* _ENDWORD is a terminal symbol that matches
  281. X                   the empty string if it is at the end of
  282. X                   a word. */
  283. X
  284. X  _LIMWORD,            /* _LIMWORD is a terminal symbol that matches
  285. X                   the empty string if it is at the beginning
  286. X                   or the end of a word. */
  287. X
  288. X  _NOTLIMWORD,            /* _NOTLIMWORD is a terminal symbol that
  289. X                   matches the empty string if it is not at
  290. X                   the beginning or end of a word. */
  291. X
  292. X  _QMARK,            /* _QMARK is an operator of one argument that
  293. X                   matches zero or one occurences of its
  294. X                   argument. */
  295. X
  296. X  _STAR,            /* _STAR is an operator of one argument that
  297. X                   matches the Kleene closure (zero or more
  298. X                   occurrences) of its argument. */
  299. X
  300. X  _PLUS,            /* _PLUS is an operator of one argument that
  301. X                   matches the positive closure (one or more
  302. X                   occurrences) of its argument. */
  303. X
  304. X  _CAT,                /* _CAT is an operator of two arguments that
  305. X                   matches the concatenation of its
  306. X                   arguments.  _CAT is never returned by the
  307. X                   lexical analyzer. */
  308. X
  309. X  _OR,                /* _OR is an operator of two arguments that
  310. X                   matches either of its arguments. */
  311. X
  312. X  _LPAREN,            /* _LPAREN never appears in the parse tree,
  313. X                   it is only a lexeme. */
  314. X
  315. X  _RPAREN,            /* _RPAREN never appears in the parse tree. */
  316. X
  317. X  _SET                /* _SET and (and any value greater) is a
  318. X                   terminal symbol that matches any of a
  319. X                   class of characters. */
  320. X} _token;
  321. X
  322. X#else /* ! __STDC__ */
  323. X
  324. Xtypedef short _token;
  325. X
  326. X#define _END -1
  327. X#define _EMPTY _NOTCHAR
  328. X#define _BACKREF (_EMPTY + 1)
  329. X#define _BEGLINE (_EMPTY + 2)
  330. X#define _ALLBEGLINE (_EMPTY + 3)
  331. X#define _ENDLINE (_EMPTY + 4)
  332. X#define _ALLENDLINE (_EMPTY + 5)
  333. X#define _BEGWORD (_EMPTY + 6)
  334. X#define _ENDWORD (_EMPTY + 7)
  335. X#define _LIMWORD (_EMPTY + 8)
  336. X#define _NOTLIMWORD (_EMPTY + 9)
  337. X#define _QMARK (_EMPTY + 10)
  338. X#define _STAR (_EMPTY + 11)
  339. X#define _PLUS (_EMPTY + 12)
  340. X#define _CAT (_EMPTY + 13)
  341. X#define _OR (_EMPTY + 14)
  342. X#define _LPAREN (_EMPTY + 15)
  343. X#define _RPAREN (_EMPTY + 16)
  344. X#define _SET (_EMPTY + 17)
  345. X
  346. X#endif /* ! __STDC__ */
  347. X
  348. X/* Sets are stored in an array in the compiled regexp; the index of the
  349. X   array corresponding to a given set token is given by _SET_INDEX(t). */
  350. X#define _SET_INDEX(t) ((t) - _SET)
  351. X
  352. X/* Sometimes characters can only be matched depending on the surrounding
  353. X   context.  Such context decisions depend on what the previous character
  354. X   was, and the value of the current (lookahead) character.  Context
  355. X   dependent constraints are encoded as 8 bit integers.  Each bit that
  356. X   is set indicates that the constraint succeeds in the corresponding
  357. X   context.
  358. X
  359. X   bit 7 - previous and current are newlines
  360. X   bit 6 - previous was newline, current isn't
  361. X   bit 5 - previous wasn't newline, current is
  362. X   bit 4 - neither previous nor current is a newline
  363. X   bit 3 - previous and current are word-constituents
  364. X   bit 2 - previous was word-constituent, current isn't
  365. X   bit 1 - previous wasn't word-constituent, current is
  366. X   bit 0 - neither previous nor current is word-constituent
  367. X
  368. X   Word-constituent characters are those that satisfy isalnum().
  369. X
  370. X   The macro _SUCCEEDS_IN_CONTEXT determines whether a a given constraint
  371. X   succeeds in a particular context.  Prevn is true if the previous character
  372. X   was a newline, currn is true if the lookahead character is a newline.
  373. X   Prevl and currl similarly depend upon whether the previous and current
  374. X   characters are word-constituent letters. */
  375. X#define _MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn) \
  376. X  ((constraint) & 1 << ((prevn) ? 2 : 0) + ((currn) ? 1 : 0) + 4)
  377. X#define _MATCHES_LETTER_CONTEXT(constraint, prevl, currl) \
  378. X  ((constraint) & 1 << ((prevl) ? 2 : 0) + ((currl) ? 1 : 0))
  379. X#define _SUCCEEDS_IN_CONTEXT(constraint, prevn, currn, prevl, currl) \
  380. X  (_MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn)             \
  381. X   && _MATCHES_LETTER_CONTEXT(constraint, prevl, currl))
  382. X
  383. X/* The following macros give information about what a constraint depends on. */
  384. X#define _PREV_NEWLINE_DEPENDENT(constraint) \
  385. X  (((constraint) & 0xc0) >> 2 != ((constraint) & 0x30))
  386. X#define _PREV_LETTER_DEPENDENT(constraint) \
  387. X  (((constraint) & 0x0c) >> 2 != ((constraint) & 0x03))
  388. X
  389. X/* Tokens that match the empty string subject to some constraint actually
  390. X   work by applying that constraint to determine what may follow them,
  391. X   taking into account what has gone before.  The following values are
  392. X   the constraints corresponding to the special tokens previously defined. */
  393. X#define _NO_CONSTRAINT 0xff
  394. X#define _BEGLINE_CONSTRAINT 0xcf
  395. X#define _ENDLINE_CONSTRAINT 0xaf
  396. X#define _BEGWORD_CONSTRAINT 0xf2
  397. X#define _ENDWORD_CONSTRAINT 0xf4
  398. X#define _LIMWORD_CONSTRAINT 0xf6
  399. X#define _NOTLIMWORD_CONSTRAINT 0xf9
  400. X
  401. X/* States of the recognizer correspond to sets of positions in the parse
  402. X   tree, together with the constraints under which they may be matched.
  403. X   So a position is encoded as an index into the parse tree together with
  404. X   a constraint. */
  405. Xtypedef struct
  406. X{
  407. X  unsigned index:24,        /* Index into the parse array. */
  408. X       constraint:8;    /* Constraint for matching this position. */
  409. X} _position;
  410. X
  411. X/* Sets of positions are stored as arrays. */
  412. Xtypedef struct
  413. X{
  414. X  _position *elems;        /* Elements of this position set. */
  415. X  int nelem;            /* Number of elements in this set. */
  416. X} _position_set;
  417. X
  418. X/* A state of the regexp consists of a set of positions, some flags,
  419. X   and the token value of the lowest-numbered position of the state that
  420. X   contains an _END token. */
  421. Xtypedef struct
  422. X{
  423. X  int hash;            /* Hash of the positions of this state. */
  424. X  _position_set elems;        /* Positions this state could match. */
  425. X  unsigned newline:1,        /* True if previous state matched newline. */
  426. X       letter:1,        /* True if previous state matched a letter. */
  427. X       backref:1,        /* True if this state matches a \<digit>. */
  428. X       constraint:8;    /* Constraint for this state to accept. */
  429. X  int first_end;        /* Token value of the first _END in elems. */
  430. X} _dfa_state;
  431. X
  432. X/* If an r.e. is at most MUST_MAX characters long, we look for a string which
  433. X   must appear in it; whatever's found is dropped into the struct reg. */
  434. X
  435. X#define MUST_MAX    50
  436. X
  437. X/* A compiled regular expression. */
  438. Xstruct regexp
  439. X{
  440. X  /* Stuff built by the scanner. */
  441. X  _charset *charsets;        /* Array of character sets for _SET tokens. */
  442. X  int cindex;            /* Index for adding new charsets. */
  443. X  int calloc;            /* Number of charsets currently allocated. */
  444. X
  445. X  /* Stuff built by the parser. */
  446. X  _token *tokens;        /* Postfix parse array. */
  447. X  int tindex;            /* Index for adding new tokens. */
  448. X  int talloc;            /* Number of tokens currently allocated. */
  449. X  int depth;            /* Depth required of an evaluation stack
  450. X                   used for depth-first traversal of the
  451. X                   parse tree. */
  452. X  int nleaves;            /* Number of leaves on the parse tree. */
  453. X  int nregexps;            /* Count of parallel regexps being built
  454. X                   with regparse(). */
  455. X
  456. X  /* Stuff owned by the state builder. */
  457. X  _dfa_state *states;        /* States of the regexp. */
  458. X  int sindex;            /* Index for adding new states. */
  459. X  int salloc;            /* Number of states currently allocated. */
  460. X
  461. X  /* Stuff built by the structure analyzer. */
  462. X  _position_set *follows;    /* Array of follow sets, indexed by position
  463. X                   index.  The follow of a position is the set
  464. X                   of positions containing characters that
  465. X                   could conceivably follow a character
  466. X                   matching the given position in a string
  467. X                   matching the regexp.  Allocated to the
  468. X                   maximum possible position index. */
  469. X  int searchflag;        /* True if we are supposed to build a searching
  470. X                   as opposed to an exact matcher.  A searching
  471. X                   matcher finds the first and shortest string
  472. X                   matching a regexp anywhere in the buffer,
  473. X                   whereas an exact matcher finds the longest
  474. X                   string matching, but anchored to the
  475. X                   beginning of the buffer. */
  476. X
  477. X  /* Stuff owned by the executor. */
  478. X  int tralloc;            /* Number of transition tables that have
  479. X                   slots so far. */
  480. X  int trcount;            /* Number of transition tables that have
  481. X                   actually been built. */
  482. X  int **trans;            /* Transition tables for states that can
  483. X                   never accept.  If the transitions for a
  484. X                   state have not yet been computed, or the
  485. X                   state could possibly accept, its entry in
  486. X                   this table is NULL. */
  487. X  int **realtrans;        /* Trans always points to realtrans + 1; this
  488. X                   is so trans[-1] can contain NULL. */
  489. X  int **fails;            /* Transition tables after failing to accept
  490. X                   on a state that potentially could do so. */
  491. X  int *success;            /* Table of acceptance conditions used in
  492. X                   regexecute and computed in build_state. */
  493. X  int *newlines;        /* Transitions on newlines.  The entry for a
  494. X                   newline in any transition table is always
  495. X                   -1 so we can count lines without wasting
  496. X                   too many cycles.  The transition for a
  497. X                   newline is stored separately and handled
  498. X                   as a special case.  Newline is also used
  499. X                   as a sentinel at the end of the buffer. */
  500. X  char must[MUST_MAX];
  501. X  int mustn;
  502. X};
  503. X
  504. X/* Some macros for user access to regexp internals. */
  505. X
  506. X/* ACCEPTING returns true if s could possibly be an accepting state of r. */
  507. X#define ACCEPTING(s, r) ((r).states[s].constraint)
  508. X
  509. X/* ACCEPTS_IN_CONTEXT returns true if the given state accepts in the
  510. X   specified context. */
  511. X#define ACCEPTS_IN_CONTEXT(prevn, currn, prevl, currl, state, reg) \
  512. X  _SUCCEEDS_IN_CONTEXT((reg).states[state].constraint,           \
  513. X               prevn, currn, prevl, currl)
  514. X
  515. X/* FIRST_MATCHING_REGEXP returns the index number of the first of parallel
  516. X   regexps that a given state could accept.  Parallel regexps are numbered
  517. X   starting at 1. */
  518. X#define FIRST_MATCHING_REGEXP(state, reg) (-(reg).states[state].first_end)
  519. X
  520. X/* Entry points. */
  521. X
  522. X#ifdef __STDC__
  523. X
  524. X/* Regsyntax() takes two arguments; the first sets the syntax bits described
  525. X   earlier in this file, and the second sets the case-folding flag. */
  526. Xextern void regsyntax(int, int);
  527. X
  528. X/* Compile the given string of the given length into the given struct regexp.
  529. X   Final argument is a flag specifying whether to build a searching or an
  530. X   exact matcher. */
  531. Xextern void regcompile(const char *, size_t, struct regexp *, int);
  532. X
  533. X/* Execute the given struct regexp on the buffer of characters.  The
  534. X   first char * points to the beginning, and the second points to the
  535. X   first character after the end of the buffer, which must be a writable
  536. X   place so a sentinel end-of-buffer marker can be stored there.  The
  537. X   second-to-last argument is a flag telling whether to allow newlines to
  538. X   be part of a string matching the regexp.  The next-to-last argument,
  539. X   if non-NULL, points to a place to increment every time we see a
  540. X   newline.  The final argument, if non-NULL, points to a flag that will
  541. X   be set if further examination by a backtracking matcher is needed in
  542. X   order to verify backreferencing; otherwise the flag will be cleared.
  543. X   Returns NULL if no match is found, or a pointer to the first
  544. X   character after the first & shortest matching string in the buffer. */
  545. Xextern char *regexecute(struct regexp *, char *, char *, int, int *, int *);
  546. X
  547. X/* Free the storage held by the components of a struct regexp. */
  548. Xextern void regfree(struct regexp *);
  549. X
  550. X/* Entry points for people who know what they're doing. */
  551. X
  552. X/* Initialize the components of a struct regexp. */
  553. Xextern void reginit(struct regexp *);
  554. X
  555. X/* Incrementally parse a string of given length into a struct regexp. */
  556. Xextern void regparse(const char *, size_t, struct regexp *);
  557. X
  558. X/* Analyze a parsed regexp; second argument tells whether to build a searching
  559. X   or an exact matcher. */
  560. Xextern void reganalyze(struct regexp *, int);
  561. X
  562. X/* Compute, for each possible character, the transitions out of a given
  563. X   state, storing them in an array of integers. */
  564. Xextern void regstate(int, struct regexp *, int []);
  565. X
  566. X/* Error handling. */
  567. X
  568. X/* Regerror() is called by the regexp routines whenever an error occurs.  It
  569. X   takes a single argument, a NUL-terminated string describing the error.
  570. X   The default regerror() prints the error message to stderr and exits.
  571. X   The user can provide a different regfree() if so desired. */
  572. Xextern void regerror(const char *);
  573. X
  574. X#else /* ! __STDC__ */
  575. Xextern void regsyntax(), regcompile(), regfree(), reginit(), regparse();
  576. Xextern void reganalyze(), regstate(), regerror();
  577. Xextern char *regexecute();
  578. X#endif
  579. END_OF_FILE
  580. if test 22427 -ne `wc -c <'dfa.h'`; then
  581.     echo shar: \"'dfa.h'\" unpacked with wrong size!
  582. fi
  583. # end of 'dfa.h'
  584. fi
  585. if test -f 'grep.c' -a "${1}" != "-c" ; then 
  586.   echo shar: Will not clobber existing file \"'grep.c'\"
  587. else
  588. echo shar: Extracting \"'grep.c'\" \(28346 characters\)
  589. sed "s/^X//" >'grep.c' <<'END_OF_FILE'
  590. X/* grep - print lines matching an extended regular expression
  591. X   Copyright (C) 1988 Free Software Foundation, Inc.
  592. X                      Written June, 1988 by Mike Haertel
  593. X                  BMG speedups added July, 1988
  594. X            by James A. Woods and Arthur David Olson
  595. X
  596. X               NO WARRANTY
  597. X
  598. X  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  599. XNO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  600. XWHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  601. XRICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  602. XWITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  603. XBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  604. XFITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  605. XAND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  606. XDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  607. XCORRECTION.
  608. X
  609. X IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  610. XSTALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  611. XWHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  612. XLIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  613. XOTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  614. XUSE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  615. XDATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  616. XA FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  617. XPROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  618. XDAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  619. X
  620. X        GENERAL PUBLIC LICENSE TO COPY
  621. X
  622. X  1. You may copy and distribute verbatim copies of this source file
  623. Xas you receive it, in any medium, provided that you conspicuously and
  624. Xappropriately publish on each copy a valid copyright notice "Copyright
  625. X (C) 1988 Free Software Foundation, Inc."; and include following the
  626. Xcopyright notice a verbatim copy of the above disclaimer of warranty
  627. Xand of this License.  You may charge a distribution fee for the
  628. Xphysical act of transferring a copy.
  629. X
  630. X  2. You may modify your copy or copies of this source file or
  631. Xany portion of it, and copy and distribute such modifications under
  632. Xthe terms of Paragraph 1 above, provided that you also do the following:
  633. X
  634. X    a) cause the modified files to carry prominent notices stating
  635. X    that you changed the files and the date of any change; and
  636. X
  637. X    b) cause the whole of any work that you distribute or publish,
  638. X    that in whole or in part contains or is a derivative of this
  639. X    program or any part thereof, to be licensed at no charge to all
  640. X    third parties on terms identical to those contained in this
  641. X    License Agreement (except that you may choose to grant more extensive
  642. X    warranty protection to some or all third parties, at your option).
  643. X
  644. X    c) You may charge a distribution fee for the physical act of
  645. X    transferring a copy, and you may at your option offer warranty
  646. X    protection in exchange for a fee.
  647. X
  648. XMere aggregation of another unrelated program with this program (or its
  649. Xderivative) on a volume of a storage or distribution medium does not bring
  650. Xthe other program under the scope of these terms.
  651. X
  652. X  3. You may copy and distribute this program or any portion of it in
  653. Xcompiled, executable or object code form under the terms of Paragraphs
  654. X1 and 2 above provided that you do the following:
  655. X
  656. X    a) accompany it with the complete corresponding machine-readable
  657. X    source code, which must be distributed under the terms of
  658. X    Paragraphs 1 and 2 above; or,
  659. X
  660. X    b) accompany it with a written offer, valid for at least three
  661. X    years, to give any third party free (except for a nominal
  662. X    shipping charge) a complete machine-readable copy of the
  663. X    corresponding source code, to be distributed under the terms of
  664. X    Paragraphs 1 and 2 above; or,
  665. X
  666. X    c) accompany it with the information you received as to where the
  667. X    corresponding source code may be obtained.  (This alternative is
  668. X    allowed only for noncommercial distribution and only if you
  669. X    received the program in object code or executable form alone.)
  670. X
  671. XFor an executable file, complete source code means all the source code for
  672. Xall modules it contains; but, as a special exception, it need not include
  673. Xsource code for modules which are standard libraries that accompany the
  674. Xoperating system on which the executable file runs.
  675. X
  676. X  4. You may not copy, sublicense, distribute or transfer this program
  677. Xexcept as expressly provided under this License Agreement.  Any attempt
  678. Xotherwise to copy, sublicense, distribute or transfer this program is void and
  679. Xyour rights to use the program under this License agreement shall be
  680. Xautomatically terminated.  However, parties who have received computer
  681. Xsoftware programs from you with this License Agreement will not have
  682. Xtheir licenses terminated so long as such parties remain in full compliance.
  683. X
  684. X  5. If you wish to incorporate parts of this program into other free
  685. Xprograms whose distribution conditions are different, write to the Free
  686. XSoftware Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  687. Xworked out a simple rule that can be stated here, but we will often permit
  688. Xthis.  We will be guided by the two goals of preserving the free status of
  689. Xall derivatives our free software and of promoting the sharing and reuse of
  690. Xsoftware.
  691. X
  692. X
  693. XIn other words, you are welcome to use, share and improve this program.
  694. XYou are forbidden to forbid anyone else to use, share and improve
  695. Xwhat you give them.   Help stamp out software-hoarding!  */
  696. X
  697. X#include <ctype.h>
  698. X#include <stdio.h>
  699. X#ifdef USG
  700. X#include <memory.h>
  701. X#include <string.h>
  702. X#else
  703. X#include <strings.h>
  704. X#endif
  705. X#include "dfa.h"
  706. X#include "regex.h"
  707. X
  708. X#ifdef __STDC__
  709. Xextern getopt(int, char **, const char *);
  710. Xextern read(int, void *, int);
  711. Xextern open(const char *, int, ...);
  712. Xextern void close();
  713. X#else
  714. Xextern char *strrchr();
  715. X#endif
  716. X
  717. Xextern char *optarg;
  718. Xextern optind, opterr;
  719. Xextern errno;
  720. Xextern char *sys_errlist[];
  721. X
  722. X#define MAX(a, b) ((a) > (b) ? (a) : (b))
  723. X
  724. X/* Exit status codes. */
  725. X#define MATCHES_FOUND 0        /* Exit 0 if no errors and matches found. */
  726. X#define NO_MATCHES_FOUND 1    /* Exit 1 if no matches were found. */
  727. X#define ERROR 2            /* Exit 2 if some error occurred. */
  728. X
  729. X/* Error is set true if something awful happened. */
  730. Xstatic int error;
  731. X
  732. X/* The program name for error messages. */
  733. Xstatic char *prog;
  734. X
  735. X/* We do all our own buffering by hand for efficiency. */
  736. Xstatic char *buffer;        /* The buffer itself, grown as needed. */
  737. Xstatic bufbytes;        /* Number of bytes in the buffer. */
  738. Xstatic size_t bufalloc;        /* Number of bytes allocated to the buffer. */
  739. Xstatic bufprev;            /* Number of bytes that have been forgotten.
  740. X                   This is used to get byte offsets from the
  741. X                   beginning of the file. */
  742. Xstatic bufread;            /* Number of bytes to get with each read(). */
  743. X
  744. Xstatic void
  745. Xinitialize_buffer()
  746. X{
  747. X  bufread = 8192;
  748. X  bufalloc = bufread + bufread / 2;
  749. X  buffer = malloc(bufalloc);
  750. X  if (! buffer)
  751. X    {
  752. X      fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  753. X          sys_errlist[errno]);
  754. X      exit(ERROR);
  755. X    }
  756. X}
  757. X
  758. X/* The current input file. */
  759. Xstatic fd;
  760. Xstatic char *filename;
  761. Xstatic eof;
  762. X
  763. X/* Fill the buffer retaining the last n bytes at the beginning of the
  764. X   newly filled buffer (for backward context).  Returns the number of new
  765. X   bytes read from disk. */
  766. Xstatic
  767. Xfill_buffer_retaining(n)
  768. X     int n;
  769. X{
  770. X  char *p, *q;
  771. X  int i;
  772. X
  773. X  /* See if we need to grow the buffer. */
  774. X  if (bufalloc - n <= bufread)
  775. X    {
  776. X      while (bufalloc - n <= bufread)
  777. X    {
  778. X      bufalloc *= 2;
  779. X      bufread *= 2;
  780. X    }
  781. X      buffer = realloc(buffer, bufalloc);
  782. X      if (! buffer)
  783. X    {
  784. X      fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  785. X          sys_errlist[errno]);
  786. X      exit(ERROR);
  787. X    }
  788. X    }
  789. X
  790. X  bufprev += bufbytes - n;
  791. X
  792. X  /* Shift stuff down. */
  793. X  for (i = n, p = buffer, q = p + bufbytes - n; i--; )
  794. X    *p++ = *q++;
  795. X  bufbytes = n;
  796. X
  797. X  if (eof)
  798. X    return 0;
  799. X
  800. X  /* Read in new stuff. */
  801. X  i = read(fd, buffer + bufbytes, bufread);
  802. X  if (i < 0)
  803. X    {
  804. X      fprintf(stderr, "%s: read on %s failed (%s)\n", prog,
  805. X          filename ? filename : "<stdin>", sys_errlist[errno]);
  806. X      error = 1;
  807. X    }
  808. X
  809. X  /* Kludge to pretend every nonempty file ends with a newline. */
  810. X  if (i == 0 && bufbytes > 0 && buffer[bufbytes - 1] != '\n')
  811. X    {
  812. X      eof = i = 1;
  813. X      buffer[bufbytes] = '\n';
  814. X    }
  815. X
  816. X  bufbytes += i;
  817. X  return i;
  818. X}
  819. X
  820. X/* Various flags set according to the argument switches. */
  821. Xstatic trailing_context;    /* Lines of context to show after matches. */
  822. Xstatic leading_context;        /* Lines of context to show before matches. */
  823. Xstatic byte_count;        /* Precede output lines the byte count of the
  824. X                   first character on the line. */
  825. Xstatic no_filenames;        /* Do not display filenames. */
  826. Xstatic line_numbers;        /* Precede output lines with line numbers. */
  827. Xstatic silent;            /* Produce no output at all.  This switch
  828. X                   is bogus, ever hear of /dev/null? */
  829. Xstatic nonmatching_lines;    /* Print lines that don't match the regexp. */
  830. X
  831. Xstatic bmgexec;            /* Invoke Boyer-Moore-Gosper routines */
  832. X
  833. X/* The compiled regular expression lives here. */
  834. Xstatic struct regexp reg;
  835. X
  836. X/* The compiled regular expression for the backtracking matcher lives here. */
  837. Xstatic struct re_pattern_buffer regex;
  838. X
  839. X/* Pointer in the buffer after the last character printed. */
  840. Xstatic char *printed_limit;
  841. X
  842. X/* True when printed_limit has been artifically advanced without printing
  843. X   anything. */
  844. Xstatic int printed_limit_fake;
  845. X
  846. X/* Print a line at the given line number, returning the number of
  847. X   characters actually printed.  Matching is true if the line is to
  848. X   be considered a "matching line".  This is only meaningful if
  849. X   surrounding context is turned on. */
  850. Xstatic
  851. Xprint_line(p, number, matching)
  852. X     char *p;
  853. X     int number;
  854. X     int matching;
  855. X{
  856. X  int count = 0;
  857. X
  858. X  if (silent)
  859. X    {
  860. X      do
  861. X    ++count;
  862. X      while (*p++ != '\n');
  863. X      printed_limit_fake = 0;
  864. X      printed_limit = p;
  865. X      return count;
  866. X    }
  867. X
  868. X  if (filename && !no_filenames)
  869. X    printf("%s%c", filename, matching ? ':' : '-');
  870. X  if (byte_count)
  871. X    printf("%d%c", p - buffer + bufprev, matching ? ':' : '-');
  872. X  if (line_numbers)
  873. X    printf("%d%c", number, matching ? ':' : '-');
  874. X  do
  875. X    {
  876. X      ++count;
  877. X      putchar(*p);
  878. X    }
  879. X  while (*p++ != '\n');
  880. X  printed_limit_fake = 0;
  881. X  printed_limit = p;
  882. X  return count;
  883. X}
  884. X
  885. X/* Print matching or nonmatching lines from the current file.  Returns a
  886. X   count of matching or nonmatching lines. */
  887. Xstatic
  888. Xgrep()
  889. X{
  890. X  int retain = 0;        /* Number of bytes to retain on next call
  891. X                   to fill_buffer_retaining(). */
  892. X  char *search_limit;        /* Pointer to the character after the last
  893. X                   newline in the buffer. */
  894. X  char saved_char;        /* Character after the last newline. */
  895. X  char *resume;            /* Pointer to where to resume search. */
  896. X  int resume_index = 0;        /* Count of characters to ignore after
  897. X                   refilling the buffer. */
  898. X  int line_count = 1;        /* Line number. */
  899. X  int try_backref;        /* Set to true if we need to verify the
  900. X                   match with a backtracking matcher. */
  901. X  int initial_line_count;    /* Line count at beginning of last search. */
  902. X  char *match;            /* Pointer to the first character after the
  903. X                   string matching the regexp. */
  904. X  int match_count = 0;        /* Count of matching lines. */
  905. X  char *matching_line;        /* Pointer to first character of the matching
  906. X                   line, or of the first line of context to
  907. X                   print if context is turned on. */
  908. X  char *real_matching_line;    /* Pointer to the first character of the
  909. X                   real matching line. */
  910. X  char *next_line;        /* Pointer to first character of the line
  911. X                   following the matching line. */
  912. X  int pending_lines = 0;    /* Lines of context left over from last match
  913. X                   that we have to print. */
  914. X  static first_match = 1;    /* True when nothing has been printed. */
  915. X  int i;
  916. X  char *tmp;
  917. X  char *execute();
  918. X
  919. X  printed_limit_fake = 0;
  920. X  
  921. X  while (fill_buffer_retaining(retain) > 0)
  922. X    {
  923. X      /* Find the last newline in the buffer. */
  924. X      search_limit = buffer + bufbytes;
  925. X      while (search_limit > buffer && search_limit[-1] != '\n')
  926. X    --search_limit;
  927. X      if (search_limit == buffer)
  928. X    {
  929. X      retain = bufbytes;
  930. X      continue;
  931. X    }
  932. X
  933. X      /* Save the character after the last newline so regexecute can write
  934. X     its own sentinel newline. */
  935. X      saved_char = *search_limit;
  936. X
  937. X      /* Search the buffer for a match. */
  938. X      printed_limit = buffer;
  939. X      resume = buffer + resume_index;
  940. X      initial_line_count = line_count;
  941. X
  942. X      while (match = execute(®, resume, search_limit, 0, &line_count, &try_backref))
  943. X    {
  944. X      ++match_count;
  945. X
  946. X      /* Find the beginning of the matching line. */
  947. X      matching_line = match;
  948. X      while (matching_line > resume && matching_line[-1] != '\n')
  949. X        --matching_line;
  950. X      real_matching_line = matching_line;
  951. X
  952. X      /* Find the beginning of the next line. */
  953. X      next_line = match;
  954. X      while (next_line < search_limit && *next_line++ != '\n')
  955. X        ;
  956. X
  957. X      /* If a potential backreference is indicated, try it out with
  958. X         a backtracking matcher to make sure the line is a match. */
  959. X      if (try_backref && re_search(®ex, matching_line,
  960. X                       next_line - matching_line,
  961. X                       0,
  962. X                       next_line - matching_line,
  963. X                       NULL) < 0)
  964. X        {
  965. X          resume = next_line;
  966. X          if (resume == search_limit)
  967. X        break;
  968. X          else
  969. X        continue;
  970. X        }
  971. X
  972. X      /* Print leftover lines from last time.  If nonmatching_lines is
  973. X         turned on, print these as if they were matching lines. */
  974. X      while (resume < matching_line && pending_lines)
  975. X        {
  976. X          resume += print_line(resume, initial_line_count++,
  977. X                   nonmatching_lines);
  978. X          --pending_lines;
  979. X        }
  980. X
  981. X      /* Print out the matching or nonmatching lines as necessary. */
  982. X      if (! nonmatching_lines)
  983. X        {
  984. X          /* Back up over leading context if necessary. */
  985. X          for (i = leading_context; matching_line > printed_limit
  986. X           && i; --i)
  987. X        {
  988. X          while (matching_line > printed_limit
  989. X             && (--matching_line)[-1] != '\n')
  990. X            ;
  991. X          --line_count;
  992. X        }
  993. X
  994. X          /* If context is enabled, we may have to print a separator. */
  995. X          if ((leading_context || trailing_context) && !silent
  996. X          && !first_match && (printed_limit_fake || matching_line
  997. X                      > printed_limit))
  998. X        printf("----------\n");
  999. X          first_match = 0;
  1000. X
  1001. X          /* Print the matching line and its leading context. */
  1002. X          while (matching_line < real_matching_line)
  1003. X        matching_line += print_line(matching_line, line_count++, 0);
  1004. X          matching_line += print_line(matching_line, line_count++, 1);
  1005. X
  1006. X          /* If there's trailing context, leave some lines pending until
  1007. X         next time. */
  1008. X          pending_lines = trailing_context;
  1009. X        }
  1010. X      else if (matching_line > resume)
  1011. X        {
  1012. X          char *real_resume = resume;
  1013. X
  1014. X          /* Back up over leading context if necessary. */
  1015. X          for (i = leading_context; resume > printed_limit && i; --i)
  1016. X        {
  1017. X          while (resume > printed_limit && (--resume)[-1] != '\n')
  1018. X            ;
  1019. X          --initial_line_count;
  1020. X        }
  1021. X
  1022. X          /* If context is enabled, we may have to print a separator. */
  1023. X          if ((leading_context || trailing_context) && !silent
  1024. X          && !first_match && (printed_limit_fake || resume
  1025. X                      > printed_limit))
  1026. X        printf("----------\n");
  1027. X          first_match = 0;
  1028. X
  1029. X          /* Print out the presumably matching leading context. */
  1030. X          while (resume < real_resume)
  1031. X        resume += print_line(resume, initial_line_count++, 0);
  1032. X
  1033. X          /* Print out the nonmatching lines prior to the matching line. */
  1034. X          while (resume < matching_line)
  1035. X        resume += print_line(resume, initial_line_count++, 1);
  1036. X
  1037. X          /* Deal with trailing context. */
  1038. X          if (trailing_context)
  1039. X        {
  1040. X          print_line(matching_line, line_count, 0);
  1041. X          pending_lines = trailing_context - 1;
  1042. X        }
  1043. X
  1044. X          /* Count the current line. */
  1045. X          ++line_count;
  1046. X        }
  1047. X      else
  1048. X        {
  1049. X          /* The line immediately after a matching line has to be printed
  1050. X         because it was pending. */
  1051. X          if (pending_lines > 0)
  1052. X        {
  1053. X          --pending_lines;
  1054. X          print_line(matching_line, line_count, 0);
  1055. X        }
  1056. X          ++line_count;
  1057. X        }
  1058. X
  1059. X      /* Resume searching at the beginning of the next line. */
  1060. X      initial_line_count = line_count;
  1061. X      resume = next_line;
  1062. X
  1063. X      if (resume == search_limit)
  1064. X        break;
  1065. X    }
  1066. X      /* Restore the saved character. */
  1067. X      *search_limit = saved_char;
  1068. X
  1069. X      if (! nonmatching_lines)
  1070. X    {
  1071. X      while (resume < search_limit && pending_lines)
  1072. X        {
  1073. X          resume += print_line(resume, initial_line_count++, 0);
  1074. X          --pending_lines;
  1075. X        }
  1076. X    }
  1077. X      else if (search_limit > resume)
  1078. X    {
  1079. X      char *initial_resume = resume;
  1080. X
  1081. X      /* Back up over leading context if necessary. */
  1082. X      for (i = leading_context; resume > printed_limit && i; --i)
  1083. X        {
  1084. X          while (resume > printed_limit && (--resume)[-1] != '\n')
  1085. X        ;
  1086. X          --initial_line_count;
  1087. X        }
  1088. X
  1089. X      /* If context is enabled, we may have to print a separator. */
  1090. X      if ((leading_context || trailing_context) && !silent
  1091. X          && !first_match && (printed_limit_fake || resume
  1092. X                  > printed_limit))
  1093. X        printf("----------\n");
  1094. X      first_match = 0;
  1095. X
  1096. X      /* Print out all the nonmatching lines up to the search limit. */
  1097. X      while (resume < initial_resume)
  1098. X        resume += print_line(resume, initial_line_count++, 0);
  1099. X      while (resume < search_limit)
  1100. X        resume += print_line(resume, initial_line_count++, 1);
  1101. X
  1102. X      pending_lines = trailing_context;
  1103. X      resume_index = 0;
  1104. X      retain = bufbytes - (search_limit - buffer);
  1105. X      continue;
  1106. X    }
  1107. X      
  1108. X      /* Save the trailing end of the buffer for possible use as leading
  1109. X     context in the future. */
  1110. X      i = leading_context;
  1111. X      tmp = search_limit;
  1112. X      while (tmp > printed_limit && i--)
  1113. X    while (tmp > printed_limit && (--tmp)[-1] != '\n')
  1114. X      ;
  1115. X      resume_index = search_limit - tmp;
  1116. X      retain = bufbytes - (tmp - buffer);
  1117. X      if (tmp > printed_limit)
  1118. X    printed_limit_fake = 1;
  1119. X    }
  1120. X
  1121. X  return nonmatching_lines ? line_count - match_count : match_count;
  1122. X}
  1123. X
  1124. Xvoid
  1125. Xusage_and_die()
  1126. X{
  1127. X  fprintf(stderr,
  1128. X"usage: %s [-CVbchilnsvwx] [-<num>] [-AB <num>] [-f file] [-e] expr [files]\n",
  1129. X          prog);
  1130. X  exit(ERROR);
  1131. X}
  1132. X
  1133. Xstatic char version[] = "GNU e?grep, version 1.2";
  1134. X
  1135. Xmain(argc, argv)
  1136. X     int argc;
  1137. X     char **argv;
  1138. X{
  1139. X  int c;
  1140. X  int ignore_case = 0;        /* Compile the regexp to ignore case. */
  1141. X  char *the_regexp = 0;        /* The regular expression. */
  1142. X  int regexp_len;        /* Length of the regular expression. */
  1143. X  char *regexp_file = 0;    /* File containing parallel regexps. */
  1144. X  int count_lines = 0;        /* Display only a count of matching lines. */
  1145. X  int list_files = 0;        /* Display only the names of matching files. */
  1146. X  int whole_word = 0;        /* Insist that the regexp match a word only. */
  1147. X  int whole_line = 0;        /* Insist on matching only whole lines. */
  1148. X  int line_count = 0;        /* Count of matching lines for a file. */
  1149. X  int matches_found = 0;    /* True if matches were found. */
  1150. X  char *regex_errmesg;        /* Error message from regex routines. */
  1151. X  char translate[_NOTCHAR];    /* Translate table for case conversion
  1152. X                   (needed by the backtracking matcher). */
  1153. X
  1154. X  if (prog = strrchr(argv[0], '/'))
  1155. X    ++prog;
  1156. X  else
  1157. X    prog = argv[0];
  1158. X
  1159. X  opterr = 0;
  1160. X  while ((c = getopt(argc, argv, "0123456789A:B:CVbce:f:hilnsvwx")) != EOF)
  1161. X    switch (c)
  1162. X      {
  1163. X      case '?':
  1164. X    usage_and_die();
  1165. X    break;
  1166. X
  1167. X      case '0':
  1168. X      case '1':
  1169. X      case '2':
  1170. X      case '3':
  1171. X      case '4':
  1172. X      case '5':
  1173. X      case '6':
  1174. X      case '7':
  1175. X      case '8':
  1176. X      case '9':
  1177. X    trailing_context = 10 * trailing_context + c - '0';
  1178. X    leading_context = 10 * leading_context + c - '0';
  1179. X    break;
  1180. X
  1181. X      case 'A':
  1182. X    if (! sscanf(optarg, "%d", &trailing_context)
  1183. X        || trailing_context < 0)
  1184. X      usage_and_die();
  1185. X    break;
  1186. X
  1187. X      case 'B':
  1188. X    if (! sscanf(optarg, "%d", &leading_context)
  1189. X        || leading_context < 0)
  1190. X      usage_and_die();
  1191. X    break;
  1192. X
  1193. X      case 'C':
  1194. X    trailing_context = leading_context = 2;
  1195. X    break;
  1196. X
  1197. X      case 'V':
  1198. X    fprintf(stderr, "%s\n", version);
  1199. X    break;
  1200. X
  1201. X      case 'b':
  1202. X    byte_count = 1;
  1203. X    break;
  1204. X
  1205. X      case 'c':
  1206. X    count_lines = 1;
  1207. X    silent = 1;
  1208. X    break;
  1209. X
  1210. X      case 'e':
  1211. X    /* It doesn't make sense to mix -f and -e. */
  1212. X    if (regexp_file)
  1213. X      usage_and_die();
  1214. X    the_regexp = optarg;
  1215. X    break;
  1216. X
  1217. X      case 'f':
  1218. X    /* It doesn't make sense to mix -f and -e. */
  1219. X    if (the_regexp)
  1220. X      usage_and_die();
  1221. X    regexp_file = optarg;
  1222. X    break;
  1223. X
  1224. X      case 'h':
  1225. X    no_filenames = 1;
  1226. X    break;
  1227. X
  1228. X      case 'i':
  1229. X    ignore_case = 1;
  1230. X    for (c = 0; c < _NOTCHAR; ++c)
  1231. X      if (isupper(c))
  1232. X        translate[c] = tolower(c);
  1233. X      else
  1234. X        translate[c] = c;
  1235. X    regex.translate = translate;
  1236. X    break;
  1237. X
  1238. X      case 'l':
  1239. X    list_files = 1;
  1240. X    silent = 1;
  1241. X    break;
  1242. X
  1243. X      case 'n':
  1244. X    line_numbers = 1;
  1245. X    break;
  1246. X
  1247. X      case 's':
  1248. X    silent = 1;
  1249. X    break;
  1250. X
  1251. X      case 'v':
  1252. X    nonmatching_lines = 1;
  1253. X    break;
  1254. X
  1255. X      case 'w':
  1256. X    whole_word = 1;
  1257. X    break;
  1258. X
  1259. X      case 'x':
  1260. X    whole_line = 1;
  1261. X    break;
  1262. X
  1263. X      default:
  1264. X    /* This can't happen. */
  1265. X    fprintf(stderr, "%s: getopt(3) let one by!\n", prog);
  1266. X    usage_and_die();
  1267. X    break;
  1268. X      }
  1269. X
  1270. X  /* Set the syntax depending on arg 0 and whether to ignore case. */
  1271. X  if (*prog == 'e')
  1272. X    {
  1273. X      regsyntax(RE_SYNTAX_EGREP, ignore_case);
  1274. X      re_set_syntax(RE_SYNTAX_EGREP);
  1275. X    }
  1276. X  else
  1277. X    {
  1278. X      regsyntax(RE_SYNTAX_GREP, ignore_case);
  1279. X      re_set_syntax(RE_SYNTAX_GREP);
  1280. X    }
  1281. X
  1282. X  /* Compile the regexp according to all the options. */
  1283. X  if (regexp_file)
  1284. X    {
  1285. X      FILE *fp = fopen(regexp_file, "r");
  1286. X      int len = 256;
  1287. X      int i = 0;
  1288. X
  1289. X      if (! fp)
  1290. X    {
  1291. X      fprintf(stderr, "%s: %s: %s\n", prog, regexp_file,
  1292. X          sys_errlist[errno]);
  1293. X      exit(ERROR);
  1294. X    }
  1295. X
  1296. X      the_regexp = malloc(len);
  1297. X      while ((c = getc(fp)) != EOF)
  1298. X    {
  1299. X      the_regexp[i++] = c;
  1300. X      if (i == len)
  1301. X        the_regexp = realloc(the_regexp, len *= 2);
  1302. X    }
  1303. X      /* Nuke the concluding newline so we won't match the empty string. */
  1304. X      if (i > 0 && the_regexp[i - 1] == '\n')
  1305. X    --i;
  1306. X      regexp_len = i;
  1307. X    }
  1308. X  else if (! the_regexp)
  1309. X    {
  1310. X      if (optind >= argc)
  1311. X    usage_and_die();
  1312. X      the_regexp = argv[optind++];
  1313. X      regexp_len = strlen(the_regexp);
  1314. X    }
  1315. X  else
  1316. X    regexp_len = strlen(the_regexp);
  1317. X  
  1318. X  if (whole_word || whole_line)
  1319. X    {
  1320. X      char *n = malloc(regexp_len + 8);
  1321. X      int i = 0;
  1322. X
  1323. X      if (whole_line)
  1324. X    n[i++] = '^';
  1325. X      else
  1326. X    n[i++] = '\\', n[i++] = '<';
  1327. X      if (*prog != 'e')
  1328. X    n[i++] = '\\';
  1329. X      n[i++] = '(';
  1330. X      memcpy(n + i, the_regexp, regexp_len);
  1331. X      i += regexp_len;
  1332. X      if (*prog != 'e')
  1333. X    n[i++] = '\\';
  1334. X      n[i++] = ')';
  1335. X      if (whole_line)
  1336. X    n[i++] = '$';
  1337. X      else
  1338. X    n[i++] = '\\', n[i++] = '>';
  1339. X      the_regexp = n;
  1340. X      regexp_len = i;
  1341. X    }
  1342. X
  1343. X  regcompile(the_regexp, regexp_len, ®, 1);
  1344. X  
  1345. X  if (regex_errmesg = re_compile_pattern(the_regexp, regexp_len, ®ex))
  1346. X    regerror(regex_errmesg);
  1347. X  
  1348. X  /*
  1349. X    Find the longest metacharacter-free string which must occur in the
  1350. X    regexpr, before short-circuiting regexecute() with Boyer-Moore-Gosper.
  1351. X    (Conjecture:  The problem in general is NP-complete.)  If there is no
  1352. X    such string (like for many alternations), then default to full automaton
  1353. X    search.  regmust() code and heuristics [see dfa.c] courtesy
  1354. X    Arthur David Olson.
  1355. X    */
  1356. X  if (line_numbers == 0 && nonmatching_lines == 0)
  1357. X    {
  1358. X      if (reg.mustn == 0 || reg.mustn == MUST_MAX ||
  1359. X        strchr(reg.must, '\0') != reg.must + reg.mustn)
  1360. X    bmgexec = 0;
  1361. X      else
  1362. X    {
  1363. X      reg.must[reg.mustn] = '\0';
  1364. X      if (getenv("MUSTDEBUG") != NULL)
  1365. X        (void) printf("must have: \"%s\"\n", reg.must);
  1366. X      bmg_setup(reg.must, ignore_case);
  1367. X      bmgexec = 1;
  1368. X    }
  1369. X    }
  1370. X  
  1371. X  if (argc - optind < 2)
  1372. X    no_filenames = 1;
  1373. X
  1374. X  initialize_buffer();
  1375. X
  1376. X  if (argc > optind)
  1377. X    while (optind < argc)
  1378. X      {
  1379. X    bufprev = eof = 0;
  1380. X    filename = argv[optind++];
  1381. X    fd = open(filename, 0, 0);
  1382. X    if (fd < 0)
  1383. X      {
  1384. X        fprintf(stderr, "%s: %s: %s\n", prog, filename,
  1385. X            sys_errlist[errno]);
  1386. X        error = 1;
  1387. X        continue;
  1388. X      }
  1389. X    if (line_count = grep())
  1390. X      matches_found = 1;
  1391. X    close(fd);
  1392. X    if (count_lines)
  1393. X      if (!no_filenames)
  1394. X        printf("%s:%d\n", filename, line_count);
  1395. X      else
  1396. X        printf("%d\n", line_count);
  1397. X    else if (list_files && line_count)
  1398. X      printf("%s\n", filename);
  1399. X      }
  1400. X  else
  1401. X    {
  1402. X      if (line_count = grep())
  1403. X    matches_found = 1;
  1404. X      if (count_lines)
  1405. X    printf("%d\n", line_count);
  1406. X      else if (list_files && line_count)
  1407. X    printf("<stdin>\n");
  1408. X    }
  1409. X
  1410. X  if (error)
  1411. X    exit(ERROR);
  1412. X  if (matches_found)
  1413. X    exit(MATCHES_FOUND);
  1414. X  exit(NO_MATCHES_FOUND);
  1415. X}
  1416. X
  1417. X/* Needed by the regexp routines.  This could be fancier, especially when
  1418. X   dealing with parallel regexps in files. */
  1419. Xvoid
  1420. Xregerror(s)
  1421. X     const char *s;
  1422. X{
  1423. X  fprintf(stderr, "%s: %s\n", prog, s);
  1424. X  exit(ERROR);
  1425. X}
  1426. X
  1427. X/*
  1428. X   bmg_setup() and bmg_search() adapted from:
  1429. X     Boyer/Moore/Gosper-assisted 'egrep' search, with delta0 table as in
  1430. X     original paper (CACM, October, 1977).  No delta1 or delta2.  According to
  1431. X     experiment (Horspool, Soft. Prac. Exp., 1982), delta2 is of minimal
  1432. X     practical value.  However, to improve for worst case input, integrating
  1433. X     the improved Galil strategies (Apostolico/Giancarlo, Siam. J. Comput.,
  1434. X     February 1986) deserves consideration.
  1435. X
  1436. X     James A. Woods                Copyleft (C) 1986, 1988
  1437. X     NASA Ames Research Center
  1438. X*/
  1439. X
  1440. Xchar *
  1441. Xexecute(r, begin, end, newline, count, try_backref)
  1442. X  struct regexp *r;
  1443. X  char *begin;
  1444. X  char *end;
  1445. X  int newline;
  1446. X  int *count;
  1447. X  int *try_backref;
  1448. X{
  1449. X  register char *p, *s;
  1450. X  char *match;
  1451. X  char *start = begin;
  1452. X  char save;            /* regexecute() sentinel */
  1453. X  int len;
  1454. X  char *bmg_search();
  1455. X
  1456. X  if (!bmgexec)            /* full automaton search */
  1457. X    return(regexecute(r, begin, end, newline, count, try_backref));
  1458. X  else
  1459. X    {
  1460. X      len = end - begin; 
  1461. X      while ((match = bmg_search((unsigned char *) start, len)) != NULL)
  1462. X    {
  1463. X      p = match;        /* narrow search range to submatch line */
  1464. X      while (p > begin && *p != '\n')
  1465. X        p--;
  1466. X      s = match;
  1467. X      while (s < end && *s != '\n')
  1468. X        s++;
  1469. X      s++;
  1470. X
  1471. X      save = *s;
  1472. X      *s = '\0';
  1473. X      match = regexecute(r, p, s, newline, count, try_backref);
  1474. X      *s = save;
  1475. X
  1476. X      if (match != NULL)
  1477. X        return((char *) match);
  1478. X      else
  1479. X        {
  1480. X          start = s;
  1481. X          len = end - start;
  1482. X        }
  1483. X    }
  1484. X      return(NULL);
  1485. X    }
  1486. X}
  1487. X
  1488. X#include <ctype.h>
  1489. Xint        delta0[256];
  1490. Xunsigned char   cmap[256];        /* (un)folded characters */
  1491. Xunsigned char    pattern[5000];
  1492. Xint        patlen;
  1493. X
  1494. Xchar *
  1495. Xbmg_search(buffer, buflen)
  1496. X  unsigned char *buffer;
  1497. X  int buflen;
  1498. X{
  1499. X  register unsigned char *k, *strend, *s, *buflim;
  1500. X  register int t;
  1501. X  int j;
  1502. X
  1503. X  if (patlen > buflen)
  1504. X    return NULL;
  1505. X
  1506. X  buflim = buffer + buflen;
  1507. X  if (buflen > patlen * 4)
  1508. X    strend = buflim - patlen * 4;
  1509. X  else
  1510. X    strend = buffer;
  1511. X
  1512. X  s = buffer;
  1513. X  k = buffer + patlen - 1;
  1514. X
  1515. X  for (;;)
  1516. X    {
  1517. X      /* The dreaded inner loop, revisited. */
  1518. X      while (k < strend && (t = delta0[*k]))
  1519. X    {
  1520. X      k += t;
  1521. X      k += delta0[*k];
  1522. X      k += delta0[*k];
  1523. X    }
  1524. X      while (k < buflim && delta0[*k])
  1525. X    ++k;
  1526. X      if (k == buflim)
  1527. X    break;
  1528. X    
  1529. X      j = patlen - 1;
  1530. X      s = k;
  1531. X      while (cmap[*--s] == pattern[--j])
  1532. X    ;
  1533. X      /* 
  1534. X    delta-less shortcut for literati, but 
  1535. X    short shrift for genetic engineers.
  1536. X      */
  1537. X      if (j >= 0)
  1538. X    k++;
  1539. X      else         /* submatch */
  1540. X    return ((char *)k);
  1541. X    }
  1542. X  return(NULL);
  1543. X}
  1544. X
  1545. Xbmg_setup(pat, folded)            /* compute "boyer-moore" delta table */
  1546. X  char *pat;
  1547. X  int folded;
  1548. X{                    /* ... HAKMEM lives ... */
  1549. X  int j;
  1550. X
  1551. X  patlen = strlen(pat);
  1552. X
  1553. X  if (folded)                 /* fold case while saving pattern */
  1554. X    for (j = 0; j < patlen; j++) 
  1555. X      pattern[j] = (isupper((int) pat[j]) ?
  1556. X    (char) tolower((int) pat[j]) : pat[j]);
  1557. X  else
  1558. X      memcpy(pattern, pat, patlen);
  1559. X
  1560. X  for (j = 0; j < 256; j++)
  1561. X    {
  1562. X      delta0[j] = patlen;
  1563. X      cmap[j] = (char) j;        /* could be done at compile time */
  1564. X    }
  1565. X  for (j = 0; j < patlen - 1; j++)
  1566. X    delta0[pattern[j]] = patlen - j - 1;
  1567. X  delta0[pattern[patlen - 1]] = 0;
  1568. X
  1569. X  if (folded)
  1570. X    {
  1571. X      for (j = 0; j < patlen - 1; j++)
  1572. X    if (islower((int) pattern[j]))
  1573. X      delta0[toupper((int) pattern[j])] = patlen - j - 1;
  1574. X    if (islower((int) pattern[patlen - 1]))
  1575. X      delta0[toupper((int) pattern[patlen - 1])] = 0;
  1576. X      for (j = 'A'; j <= 'Z'; j++)
  1577. X    cmap[j] = (char) tolower((int) j);
  1578. X    }
  1579. X}
  1580. X
  1581. X#ifndef USG
  1582. X
  1583. X/* (groan) compatibility */
  1584. X
  1585. Xchar *
  1586. Xstrchr(s, c)
  1587. X     char *s;
  1588. X{
  1589. X  return index(s, c);
  1590. X}
  1591. X
  1592. Xchar *
  1593. Xstrrchr(s, c)
  1594. X     char *s;
  1595. X{
  1596. X  return rindex(s, c);
  1597. X}
  1598. X
  1599. Xchar *
  1600. Xmemcpy(d, s, n)
  1601. X     char *d, *s;
  1602. X{
  1603. X  return bcopy(s, d, n);
  1604. X}
  1605. X
  1606. X#else
  1607. X
  1608. Xchar *
  1609. Xindex(s, c)
  1610. X     char *s;
  1611. X{
  1612. X  return strchr(s, c);
  1613. X}
  1614. X
  1615. Xchar *
  1616. Xbcopy(s, d, n)
  1617. X     char *s, *d;
  1618. X{
  1619. X  return memcpy(d, s, n);
  1620. X}
  1621. X
  1622. Xchar *
  1623. Xbzero(s, n)
  1624. X     char *s;
  1625. X{
  1626. X  return memset(s, 0, n);
  1627. X}
  1628. X
  1629. Xbcmp(s, t, n)
  1630. X     char *s, *t;
  1631. X{
  1632. X  return memcmp(s, t, n);
  1633. X}
  1634. X
  1635. X#endif
  1636. END_OF_FILE
  1637. if test 28346 -ne `wc -c <'grep.c'`; then
  1638.     echo shar: \"'grep.c'\" unpacked with wrong size!
  1639. fi
  1640. # end of 'grep.c'
  1641. fi
  1642. echo shar: End of shell archive.
  1643. exit 0
  1644.  
  1645.